# -*- coding: utf-8 -*-
'''
Created on 2012-9-6


@author: Administrator
'''
import locale
import time,datetime
from service.public.service_base import ServiceBase
from helper.login_session_manager import LoginSessionManager
import json
from cgi import parse
from dbwrapper.reportx.dish_report import Dish_report
from dbwrapper.reportx.payment_report import Payment_report
from dbwrapper.reportx.sell_analysis import Sell_analysis
from dbwrapper.reportx.stat_class_report import Stat_class_report
from dbwrapper.reportx import *
import dbwrapper
from sqlalchemy.orm import class_mapper
from common.debug import Debug
import uuid

class Companyservicereport(ServiceBase):
    '''
    company report application
      
    '''

    def __init__(self,start_response):
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()

        
    def application(self, params,paths):
        
        #检查 TOKEN 的有效性 
        dbsession =self._returndbsession()
        company_id=params.getfirst("company_id");
        username=params.getfirst("username");
        token=params.getfirst("token");
        intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)
        if intcomp==False:
                return self._responseError(107, 'TOKEN 已经过期')
            
        
        #开始分流  get or set         
        if paths[2] == 'get':
            return self.getfromcompanyreportx(params)
        else:
            return self._responseError(-1, "操作失败")
             
             
        
        return self._responseError(-1, "操作失败")

      
      
    

    def getfromcompanyreportx(self, params):
        '''
            公司X库保存的统计报表      
        '''
        #TODO:       
        if params.has_key('type') == False:
            self.debug.e('Companyservicereport:no \'type\' parameters')
            return self._responseInvalidParam()
        
        
                
        config_table = params.getfirst('type')
        
        self.debug.d("tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["dish_report"] =dish_report.Dish_report
        config_table_classes["payment_report"] = payment_report.Payment_report 
        config_table_classes["sell_analysis"] = sell_analysis.Sell_analysis 
        config_table_classes["stat_class_report"] =stat_class_report.Stat_class_report 


        config_orderby = {}
        config_orderby["dish_report"] ="stat_class_name asc,dish_name asc,sold_count asc "
        config_orderby["payment_report"] = "sale_count asc "
        config_orderby["sell_analysis"] = "uuid asc "
        config_orderby["stat_class_report"] = "sort_rank asc  "
        
        config_prolist={}
        config_prolist["dish_report"] ="pro_salesrank"
        config_prolist["payment_report"] = "pro_paymentmode"
        config_prolist["sell_analysis"] = "pro_sellanalysis"
        config_prolist["stat_class_report"] = "pro_statclass"
        
        




        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby=config_orderby[config_table]
            proname=config_prolist[config_table]
            return self.getfromcompanyxAction(params, table_class,orderby,config_table,proname)
        else:
            return self._responseError(-1, "unkonw configure")
        

    def getfromcompanyxAction(self, params, table_class,orderby,config_table,proname):
        '''
                       对读配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:
            
            dbsession =self._returndbsession()
            company_id = params.getfirst('company_id')  
            start_time = params.getfirst('start_time')  
            end_time = params.getfirst('end_time')  
            
            table_class.doMapping(company_id)            

            #首先清理10分钟以前的报表记录
            dbsession.execute("set SQL_SAFE_UPDATES=0")
            dbsession.execute("delete from  report_%s.%s  where  TIMESTAMPDIFF(minute,modify_time,now())>=10 " % (company_id,config_table))            
            dbsession.commit()
            tempuuid=uuid.uuid4()            
            
            #设置参数
            tempsql_qz="set @b_t='%s'; set @e_t='%s' ;  " % (start_time,end_time)
            tempsql_qz=tempsql_qz+" set @uid='%s' ;" % tempuuid
            shopidlist=params.getfirst('shopidlist')
            shopidlist=shopidlist[1:-1].split(',')
            self.debug.e('shopidlist:%s' % shopidlist)
            for element in shopidlist:
                tempsql="use shop_order_%s_%s  ;" % (company_id,element)
                tempsql=tempsql+tempsql_qz;
                tempsql=tempsql+"  call %s(@b_t,@e_t,@uid) ; " % proname
                dbsession.execute(tempsql) 
                self.debug.e('sqlstr:%s' % tempsql)
                
                dbsession.commit()
            
            
            tempfiltername="uuid='%s'" % tempuuid;          
            #获取记录操作
            query_result = dbsession.query(table_class).filter(tempfiltername).order_by(orderby).all()            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                                                           

            self.debug.e('Companyservicereport2:%s' % repr(table_fields))
                
            returnlist=[]                
            dicmy={}
            dicmy["ret"]=0
            dicmy["msg"]='success'
            icount=0                     
            #如果是sell_analysis 就把列分装成表的形式                             
            if config_table=="sell_analysis":
                for r in query_result:
                    icount=1
                    dicmyFF={}
                    dicmyFF["sellname"]="订单总数"
                    dicmyFF["sellvalue"]=r.order_count
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="订单总金额"
                    dicmyFF["sellvalue"]=r.order_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="总消费人数"
                    dicmyFF["sellvalue"]=r.total_customer
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="最大消费金额"
                    dicmyFF["sellvalue"]=r.max_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="最小消费金额"
                    dicmyFF["sellvalue"]=r.min_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="赠送总金额"
                    dicmyFF["sellvalue"]=r.free_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="折扣总金额"
                    dicmyFF["sellvalue"]=r.discount_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="服务费"
                    dicmyFF["sellvalue"]=r.service_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmyFF={}
                    dicmyFF["sellname"]="抹零金额"
                    dicmyFF["sellvalue"]=r.zero_amount
                    strtemp=json.dumps(dicmyFF)                
                    returnlist.append(strtemp)
                    dicmy['data']=returnlist
                    return self._response(json.dumps(dicmy))
                
                
                return self._responseError(6, "记录为空")
                
                    
                    
                    
                    
            returnlist=[]                
            dicmy={}
            dicmy["ret"]=0
            dicmy["msg"]='success'
            icount=0                     
            for r in query_result:
                icount=1
                dicmyFF={} 
                for field in  table_fields:
                    temp=getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmyFF[field]=str(temp)                        
                    else:
                        dicmyFF[field]=temp
                
                    
                strtemp=json.dumps(dicmyFF)                
                returnlist.append(strtemp)
                
                
            if icount == 0:
                
                return self._responseError(6, "记录为空")   
            
            dicmy['data']=returnlist
           
            return self._response(json.dumps(dicmy))         
        except Exception, e:
           
            self.debug.e('Companyservicereport3 exception:%s' % e)
            return self._responseInvalidParam()
        

        
